<?php

namespace App\HttpController\Api\Device;

use App\Lib\Utils;
use EasySwoole\Component\Di;
use EasySwoole\Http\Message\Status;
use EasySwoole\FastCache\Cache;

use App\Model\Device\DeviceModel as DeviceModel;
use App\Model\Device\DeviceInfoModel as InfoModel;
use App\Model\Device\DeviceLogModel as LogModel;

use EasySwoole\Component\Timer;
use App\Lib\Curl;
use App\HttpController\FormatSubData;

class Register extends \App\HttpController\Api\ApiBase
{

    public function index()
    {
    	try {
    		$deviceObj = new DeviceModel();
    		$infoObj = new InfoModel();
    		$logObj = new LogModel();

    		$getData = $this->raw;
    		$actData = json_decode(Utils::characet($getData), true);
    		$sIP = $this->ip;
    		$sPort = $this->port;

    		if (!isset($actData['Name']) || ($actData['Name'] != 'registerRequest')) {

				$data['name'] = $actData['Name'];
				$data['device_id'] = $sIP.'-'.$actData['DeviceId'];
				$data['device_uuid'] = $sIP.'-'.$actData['UUID'];
				$data['device_mac'] = $sIP.'-'.$actData['Data']['DeviceInfo']['DeviceMAC'];
				$data['remark'] = '非法数据包攻击, 操作标识name为空. IP:'.$sIP;
				$data['create_time'] = time();

				$logObj->add($data);
				return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error");
    		}

    		$di = isset($actData['Data']['DeviceInfo']) ? $actData['Data']['DeviceInfo'] : [];

			$retArray = [];
			$retArray['Name'] = 'registerResponse';
			$retArray['TimeStamp'] = time();
			$retArray['Code'] = 1;
			$retArray['Message'] = 'ok';

			$DeviceId = "";
            $DeviceUUID = "";

			if (isset($di['DeviceId'])) {
                $DeviceId = trim(str_replace(array("\r\n", "\r", "\n"), "", $di['DeviceId']));
			}

			if (isset($di['DeviceUUID']) ){
                $DeviceUUID = trim(str_replace(array("\r\n", "\r", "\n"), "", $di['DeviceUUID']));
			}

			if (empty($DeviceUUID)) {

				$data['name'] = $actData['Name'];
				$deviceid = $sIP.'-';
				$data['device_uuid'] = '---';
				$data['device_mac'] = '---';
				$data['remark'] = 'register 非法数据包,device_uuid，IP：'.$sIP;
				$data['create_time'] = time();
				$logObj->add($data);

				$retArray['code'] = 0;
				$retArray['Message'] = 'DeviceUUID为空';
				$retArray['result'] = 251;
				return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error", $data);
			}


			if (empty($DeviceId)) {

				$data['name'] = $actData['Name'];
				$deviceid = $sIP.'-';
				$data['device_uuid'] = '---';
				$data['device_mac'] = '---';
				$data['remark'] = 'register 非法数据包,device_id为空，IP：'.$sIP;
				$data['create_time'] = time();
				$logObj->add($data);

				$retArray['code'] = 0;
				$retArray['Message'] = 'DeviceID为空';
				$retArray['result'] = 251;
				return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error", $data);
			}

			$dev_where['A.device_uuid'] = $DeviceUUID;
			$deviceInfo = $deviceObj->getDeviceInfo('*', $dev_where);

			if (!$deviceInfo || !is_array($deviceInfo)) {

				$data['name'] = $actData['Name'];
				$deviceid = $sIP.'-';
				$data['device_uuid'] = '---';
				$data['device_mac'] = '---';
				$data['remark'] = 'register 非法数据包,设备唯一码不存在，IP：'.$sIP;
				$data['create_time'] = time();
				$logObj->add($data);

				$retArray['code'] = 0;
				$retArray['Message'] = '设备唯一码不存在';
				$retArray['result'] = 251;
				return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error", $data);
			}

			$strSession = $DeviceUUID.'_'.$retArray['TimeStamp'];

            $data['deviceid'] = $DeviceId;
            $data['device_uuid'] = $DeviceUUID;
            $data['session'] = $strSession;

            // 第一次注册时间
			if (($deviceInfo['online_time']==NULL) || ($deviceInfo['online_time'] < 10000)) $info['onlinetime'] = $retArray['TimeStamp'];

			// 最后一次登录时间
			$data['last_login_time'] = $retArray['TimeStamp'];

			// 局域网IP, 及定义为局域网设备则更新设备地址
			if (Utils::isIP($sIP) && $deviceInfo['iswan'] == 0) {
				$data['ip'] = $sIP;
				$data['port'] = $sPort;
			}

			if( isset($actData['TimeStamp']) ) {
				$data['timestamp'] = $actData['TimeStamp'];
			}

			if (isset($di['DeviceIp'])) {
				$data['ip'] = $di['DeviceIp'];
			}

			if (isset($actData['Data']['HTTPVersion'])) {
				$data['http_version'] = $actData['Data']['HTTPVersion'];
			}

			if (isset($di['WebVersion'])) {
				$data['web_version'] = $di['WebVersion'];
			}

			if (isset($di['CoreVersion'])) {
				$data['core_version'] = $di['CoreVersion'];
			}

			if (isset($di['VersionDate'])) {
				$data['version_date'] = $di['VersionDate'];
			}

			if (isset($di['DeviceType'])) {
				$info['device_type'] = $di['DeviceType'];
			}

			if (isset($di['DeviceMac'])) {
				$info['device_mac'] = $di['DeviceMac'];
			}
			
			if (isset($di['ChannelNum'])) {
				$info['channelnum'] = $di['ChannelNum'];
			}

			$retArray['Data']['Session'] = $strSession;
			$retArray['Data']['ServerVersion'] = $actData['Data']['HTTPVersion'];

			$up_condition = [];
			$up_condition['device_uuid'] = $DeviceUUID;
			$deviceObj->update($data, $up_condition);

			$infoObj->update($info, ['devid' => $deviceInfo['id']]);

			Timer::getInstance()->after(10000, function () use($deviceObj, $DeviceUUID) {

				$formatObj = new FormatSubData();
				$curlObj = new Curl();

				// 查看更新后的信息
                $dev_where['A.device_uuid'] = $DeviceUUID;
                $deviceInfo = $deviceObj->getDeviceInfo('*', $dev_where);
                $baseINI = \Yaconf::get('basebt');

                if ($baseINI['type'] == 'cloud') {
                    if(!isset($deviceInfo['deviceuuid']) || empty($deviceInfo['deviceuuid'])){
                        return ;
                    }
                    // 云端程序，走中间件
                    $url = "http://127.0.0.1:8011/Request";
                } else {
                    if (!isset($deviceInfo['ip']) || empty($deviceInfo['ip'])) {
                        return;
                    }
                    $url = "http://{$deviceInfo['url']}:8011/Request";
                }
                $subData = $formatObj->format($deviceInfo,12);
                $result = $curlObj->request('POST', $url, $subData);
            });

			return $this->writeJsonDev($retArray);
    	} catch(\Exception $e) {
    	    echo $e->getMessage();
    		return $this->writeJson(Status::CODE_BAD_REQUEST, "Server Error");
    	}
    }
}